package com.BigDate.server.controller;


import com.BigDate.server.pojo.Experiment;
import com.BigDate.server.pojo.ForkExp;
import com.BigDate.server.pojo.RespBean;
import com.BigDate.server.pojo.RespPageBean;
import com.BigDate.server.service.IExperimentService;
import com.BigDate.server.service.IForkExpService;
import com.BigDate.server.utils.FastDFSUtils;
import com.BigDate.server.utils.pyUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author stx
 * @since 2021-12-26
 */
@RestController
@RequestMapping("/experiment")
public class ExperimentController {
    @Autowired
    private IExperimentService experimentService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private IForkExpService forkExpService;

    @ApiOperation(value = "获取所有实验(分页)")
    @GetMapping("/")
    public RespPageBean getExpByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer size, Experiment experiment){
        return experimentService.getExpByPage(currentPage,size,experiment);
    }

    @ApiOperation(value = "获取入门类")
    @GetMapping("/findPr")
    public RespBean findPr()
    {
        return RespBean.success("获取入门类成功",experimentService.findLimitPr());
    }

    @ApiOperation(value = "获取进阶类")
    @GetMapping("/findIt")
    public RespBean findIt()
    {
        return RespBean.success("获取进阶类成功",experimentService.findLimitIt());
    }

    @ApiOperation(value = "获取高级类")
    @GetMapping("/findHi")
    public RespBean findHi()
    {
        return RespBean.success("获取高级类成功",experimentService.findLimitHi());
    }

    @ApiOperation(value = "删除实验")
    @DeleteMapping("/{id}")
    public RespBean delExp(@PathVariable Integer id){
        if(experimentService.removeById(id)){
            return RespBean.success("删除实验成功!");
        }
        return RespBean.error("删除实验失败!");
    }

    @ApiOperation(value = "解析内容")
    @GetMapping("/{id}")
    public String getContent(@PathVariable Integer id){
        return experimentService.getContent(id);
    }

    @ApiOperation(value = "id查询")
    @GetMapping("/findById/{id}")
    public RespBean findById(@PathVariable("id")  Integer id){
        Experiment res = experimentService.findById(id);
        if (res != null)
        {
            return RespBean.success("请求成功",res);
        }else{
            return RespBean.error("查询的实验不存在",null);
        }
    }

    @ApiOperation(value = "运行Python")
    @GetMapping("/run/{expId}/{userId}")
    public RespBean runPython(@PathVariable("expId") Integer expId,@PathVariable("userId")Integer userId){
         return experimentService.runPython(expId,userId);
    }

    @ApiOperation(value = "添加实验")
    @PostMapping("/")
    public RespBean addExp(@RequestBody Experiment experiment){
        experiment.setContent("未添加");
        experiment.setProjectTime(new Date());
        experiment.setCollectionQuantity(20);
        if(experimentService.saveOrUpdate(experiment)){
            return RespBean.success("添加成功!");
        }
        return RespBean.error("添加失败!");
    }

    @ApiOperation(value = "通过用户ID获取用户的实验")
    @GetMapping("/getExp/{id}")
    public List<Experiment> getExpByUserId(@PathVariable Integer id){
        return experimentService.getExpByUserId(id);
    }

    @ApiOperation(value = "添加内容")
    @PostMapping("/addContent")
    public RespBean addContent(MultipartFile file,Integer projectId){
        String[] filePath = FastDFSUtils.upload(file);
        String url = FastDFSUtils.getTrackerUrl() + filePath[0] + "/" + filePath[1];
        System.out.println("url:"+url);
        System.out.println("projectId:"+projectId);
        Experiment experiment = experimentService.getById(projectId);
        experiment.setContent(url);
        experimentService.saveOrUpdate(experiment);
        System.out.println(experiment);
        return RespBean.success("添加成功!");
    }

    @ApiOperation(value = "关闭和保存Python")
    @GetMapping("/close/{projectId}")
    public RespBean closePython(String userDir,@PathVariable("projectId") Integer projectId){
        System.out.println("controller中的userdir"+userDir);
        System.out.println("上传上来的项目id:"+projectId);
        String port = redisTemplate.opsForValue().get("port");
        String pid = pyUtils.getPid(port);
        String savePath = pyUtils.killAndSave(pid, userDir);
        System.out.println("utils返回的保存路径"+savePath);
        if(savePath.isEmpty()){
            System.out.println("为空：即将保存的路径:"+savePath);
        }else {
            System.out.println("不为空 得到的路径:"+savePath);
            Experiment experiment = experimentService.getById(projectId);
            experiment.setContent(savePath);
            experimentService.saveOrUpdate(experiment);
        }
        return RespBean.success("停止成功!");
    }

    @ApiOperation(value = "删除项目")
    @DeleteMapping("/del/{projectId}")
    public RespBean delProject(@PathVariable("projectId") Integer projectId){
        List<ForkExp> expid = forkExpService.list(new QueryWrapper<ForkExp>().eq("expid", projectId));
        List<Integer> idList = new ArrayList<>();
        for (ForkExp forkExp : expid) {
            idList.add(forkExp.getId());
        }
        System.out.println(idList);
        if(!idList.isEmpty()){
            for (Integer integer : idList) {
                forkExpService.removeById(integer);
            }
        }
        if(experimentService.removeById(projectId)){
            return RespBean.success("项目删除成功!");
        }
        return RespBean.error("删除项目失败!");
    }
}
